package common

import (
	"database/sql"
	_ "github.com/mattn/go-sqlite3"
	"log"
	"os"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"time"
)

func Arg2String(excu string, arg []string) string {
	args := strings.Join(arg, " ")
	cmd := excu + " " + args
	return cmd
}

func GenLogFileName(scanType string, scanAddr string) string {
	NowTime := time.Now().Format("2006-01-02@150405")
	scanAddr = strings.Replace(scanAddr, "/", "_", -1)
	scanAddr = strings.Replace(scanAddr, ":", "_", -1)
	return scanType + "-" + scanAddr + "#" + NowTime + ".log"
}

// 字符串切片去重
func RemoveStringDuplicateNotCopy(list []string) []string {
	if list == nil {
		return nil
	}
	sort.Strings(list)
	uniq := list[:0]
	for _, x := range list {
		if len(uniq) == 0 || uniq[len(uniq)-1] != x {
			uniq = append(uniq, x)
		}
	}
	return uniq
}

func WebResultFilter(filePath string) []string {
	content, err := os.ReadFile(filePath)
	fileString := string(content)
	if err != nil {
		log.Fatalln("Error reading file:", err)
	}
	webReg := regexp.MustCompile(`http://((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}(:\d?\d?\d?\d?\d)?`)
	webURLs := webReg.FindAllString(fileString, -1)
	// 去重后输出
	return RemoveStringDuplicateNotCopy(webURLs)
}

func GenTaskID(ipAddr string) int {
	var id int = -1
	NowTime := time.Now().Unix()
	dbPath := AbsolutPath() + "/db/task.db"
	db, err := sql.Open("sqlite3", dbPath)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	tx, err := db.Begin()
	if err != nil {
		log.Fatal(err)
	}
	stmt, err := tx.Prepare("insert into task(task_ipaddr, task_start_time) values(?, ?)")
	defer stmt.Close()
	_, err = stmt.Exec(ipAddr, NowTime)
	err = tx.Commit()
	if err != nil {
		log.Fatal(err)
	}

	timeStampString := strconv.FormatInt(NowTime, 10)
	rows, err := db.Query("select id from task where task_start_time=" + "\"" + timeStampString + "\"")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	if rows.Next() {
		err = rows.Scan(&id)
		if err != nil {
			log.Fatal(err)
		}
	}
	return id
}

func UpdatePath(taskID int, pathType string, path string) bool {
	dbPath := AbsolutPath() + "/db/task.db"
	db, err := sql.Open("sqlite3", dbPath)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	updateSql := "update task set " + "\"" + pathType + "\"" + "=" + "\"" + path + "\"" +
		" where id=" + strconv.Itoa(taskID)
	//fmt.Println(updateSql)
	//return false
	_, err = db.Exec(updateSql)
	if err != nil {
		log.Fatal(err)
	}
	return true
}

func TaskTime(taskID int) string {
	taskStartTime := ""
	dbPath := AbsolutPath() + "/db/task.db"
	db, err := sql.Open("sqlite3", dbPath)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	rows, err := db.Query("select task_start_time from task where id=" + strconv.Itoa(taskID))
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	if rows.Next() {
		err = rows.Scan(&taskStartTime)
		if err != nil {
			log.Fatal(err)
		}
	}
	return taskStartTime
}
